<script setup>
import { UserService } from "@/service/UserService";
import { Md5 } from "ts-md5";
import { ref } from "vue";
import { useRouter } from "vue-router";
const router = useRouter();
const menu = ref(null);
const display = ref(false);
const props = defineProps({
    currentUser: {
        type: Object,
        default: () => ({}),
    },
});

const updatePswdItem = ref({
    oldPswd: "",
    newPswd: "",
});

const items = ref([
    {
        label: "我的主页",
        id: "client",
        icon: "pi pi-fw pi-cog",
        command: () => openClient(),
    }, {
        label: "个人资料",
        id: "profile",
        icon: "pi pi-fw pi-cog",
        command: () => openProfile(),
    },
    {
        label: "修改密码",
        id: "updatepswd",
        icon: "pi pi-fw pi-cog",
        command: () => openUpdatePswd(),
    },
    {
        separator: true,
    },
    {
        label: "退出",
        id: "exit",
        icon: "pi pi-fw   pi-desktop",
        command: () => openExit(),
    },
]);
function openClient() {
    router.push("/client/" + props.currentUser.sn);
}

function openProfile() {
    router.push("/client/" + props.currentUser.sn + "/profile");
}
function openUpdatePswd() {
    display.value = true;
}
function openExit() {
    props.currentUser = {};
    localStorage.removeItem("user");
    localStorage.removeItem("Authorization");
    router.push("/auth/login");
}

function toggleMenu(event) {
    menu.value.toggle(event);
}
function updatePswd() {
    let tempBody = new Object();
    tempBody.oldpswd = Md5.hashStr(updatePswdItem.value.oldPswd).toString();
    tempBody.newpswd = Md5.hashStr(updatePswdItem.value.newPswd).toString();

    UserService.updatePswd(props.currentUser.sn, tempBody);
    display.value = false;
}
</script>

<template>
    <div class="flex border-t lg:border-t-0 border-surface py-4 lg:py-0 mt-4 lg:mt-0 gap-2">
        <Button label="登录" as="router-link" to="/auth/login" v-if="!currentUser" rounded></Button>
        <!-- 补充完善下面SplitButton 的@click 事件，实现选择不同的下拉选项  -->
        <Menu ref="menu" :model="items" :popup="true" />
        <Button type="button" label="我的资料" icon="pi pi-angle-down" @click="toggleMenu" style="width: auto" />
    </div>
    <Dialog header="修改密码" v-model:visible="display" :breakpoints="{ '960px': '75vw' }" :style="{ width: '30vw' }"
        :modal="true">
        <p class="leading-normal p-2">
            <label for="oldPswd">旧密码:</label>
            <InputText id="oldPswd" type="text" class="mt-2 w-full" v-model="updatePswdItem.oldPswd" />
        </p>
        <p class="leading-normal p-2">
            <label for="newPswd">新密码:</label>
            <InputText id="newPswd" type="text" class="mt-2 w-full" v-model="updatePswdItem.newPswd" />
        </p>
        <template #footer>
            <Button label="保存" @click="updatePswd" />
        </template>
    </Dialog>
</template>
